#include "addfilmdialog.h"
#include "ui_addfilmdialog.h"
#include "global.h"

#include <QMessageBox>
#include <QSettings>

AddFilmDialog::AddFilmDialog(QWidget *parent) :
    film(0),
    QDialog(parent),
    ui(new Ui::AddFilmDialog)
{
    ui->setupUi(this);

    connect(ui->okButton, SIGNAL(clicked()), this, SLOT(addFilm()));

    QSettings settings;
    quint32 userid = settings.value(USER_ID, 0).toUInt();
    if (userid == 0) {
        userid = generateUserId();
        settings.setValue(USER_ID, userid);
    } else if (userid != generateUserId()) {
        QMessageBox::critical(this, tr("User Id Error"),
                              tr("Invalid user id, films reset to 0."));
        setFilmCount(0);
        userid = generateUserId();
        settings.setValue(USER_ID, userid);
    }

    ui->userIdEdit->setText(QString("%1").arg(userid, 8, 16, QChar('0')).toUpper());
}

AddFilmDialog::~AddFilmDialog()
{
    delete ui;
}

void AddFilmDialog::addFilm()
{
    bool ok;
    quint64 serial = ui->filmSerialEdit->text().toULongLong(&ok, 16);
    if (!ok) {
        QMessageBox::critical(this, tr("Add Film"), tr("Film serial format error."));
        return;
    }

    film = analyzeFilmSerial(serial);

    if (film == 0) {
        QMessageBox::critical(this, tr("Film Licence Error"),
                              tr("Invalid film licence."));
    } else {
        setFilmCount(getFilmCount()+film);
    }

    accept();
}
